#include "apue.h"

void sig_alrm(int) {}

unsigned sleep(unsigned second) {
    struct sigaction newact, oldact;
    sigset_t newmask, oldmask, suspmask;
    int unslpt;

    newact.sa_handler= sig_alrm;
    sigemptyset(&newact.sa_mask);
    newact.sa_flags= 0;
    if (sigaction(SIGALRM, &newact, &oldact) < 0) 
        err_sys("signal(SIGALRM) error");

    sigemptyset(&newmask);
    sigaddset(&newmask, SIGALRM);
    if (sigprocmask(SIG_BLOCK, &newmask, &oldmask) < 0) {
        err_sys("SIG_BLOCK error");
    }
    suspmask= oldmask;
    sigdelset(&suspmask, SIGALRM);
    
    alarm(second);
    if (sigsuspend(&suspmask) < 0)
        err_sys("sigsuspend error");
    unslpt= alarm(0);
    
    if (sigprocmask(SIG_SETMASK, &oldmask, NULL) < 0)
        err_sys("SIG_SETMASK error");

    if (sigaction(SIGALRM, &oldact, NULL) < 0)
        err_sys("signal(SIGALRM) error");
    
    return unslpt;
}
